'''
- Log
  - request from user to proxy
  - request from proxy to server
  - response from server to proxy
  - response from proxy to user
'''

import pickle
import os
import socket

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db

class Role(object):
	user = 'user'
	proxy = 'proxy'
	server = 'server'

class Item(db.Model):
	trace_id = db.StringProperty()
	create_time = db.DateTimeProperty(auto_now_add=True)
	src_role = db.CategoryProperty()
	dest_role = db.CategoryProperty()
	url = db.LinkProperty()
	headers = db.BlobProperty()
	content = db.BlobProperty()

	def headers_dict(self):
		return pickle.loads(self.headers)

def log(trace_id, src_role, dest_role, url, headers, content):
	headers = pickle.dumps(dict(headers.items()))
	# truncate the content to avoid the size of entity exceeds the limit
	content = content[:500000]
	item = Item(
		trace_id=trace_id, 
		src_role=src_role, 
		dest_role=dest_role, 
		url=url,
		headers=headers, 
		content=content
		)
	db.put(item)

class LogListPage(webapp.RequestHandler):
	def get(self):
		filter = self.request.params.get('filter', '')
		filters = [f for f in filter.split(',') if f]
		def is_filter(item):
			for filter in filters:
				if item.url.lower().endswith(filter):
					return True
		items = [item for item in Item.all().order('-create_time') if not is_filter(item)]
		path = os.path.join(os.path.dirname(__file__), 'log/list.html')
		content = template.render(path, {'items': items, 'filter': filter})
		self.response.out.write(content)

class LogShowPage(webapp.RequestHandler):
	def get(self, id):
		item = Item.get_by_id(int(id))
		path = os.path.join(os.path.dirname(__file__), 'log/show.html')
		content = template.render(path, {'item': item})
		self.response.out.write(content)

class LogClearPage(webapp.RequestHandler):
	def get(self):
		db.delete(Item.all())
		self.response.headers['Content-type'] = 'text/plain'
		self.response.out.write('Done')
